package com.cyx.spring.jdbc;

import com.cyx.spring.annotation.Autowired;
import com.cyx.spring.annotation.Bean;
import com.cyx.spring.annotation.Configuration;
import com.cyx.spring.annotation.Value;
import com.cyx.spring.tx.DataSourceTransactionManager;
import com.cyx.spring.tx.PlatformTransactionManager;
import com.cyx.spring.tx.TransactionPostProcessor;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.util.Date;

/**
 * JdbcConfiguration
 *
 * @author yongxiang
 * @date 2024/10/24 16:40
 * @desc
 */
@Configuration
public class JdbcConfiguration {

    @Bean
    public DataSource dataSource(
            // properties:
            @Value("${summer.datasource.url}") String url,
            @Value("${summer.datasource.username}") String username,
            @Value("${summer.datasource.password}") String password,
            @Value("${summer.datasource.driver-class-name}") String driver,
            @Value("${summer.datasource.maximum-pool-size:20}") Integer maximumPoolSize,
            @Value("${summer.datasource.minimum-pool-size:1}") Integer minimumPoolSize,
            @Value("${summer.datasource.connection-timeout:30000}") Integer connTimeout
    ){
        HikariConfig hikariConfig = new HikariConfig();
        var config = new HikariConfig();
        config.setAutoCommit(false);
        config.setJdbcUrl(url);
        config.setUsername(username);
        config.setPassword(password);
        if (driver != null) {
            config.setDriverClassName(driver);
        }
        config.setMaximumPoolSize(maximumPoolSize);
        config.setMinimumIdle(minimumPoolSize);
        config.setConnectionTimeout(connTimeout);
        return new HikariDataSource(config);
    }

    @Bean
    public JdbcTemplate jdbcTemplate(@Autowired DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public PlatformTransactionManager platformTransactionManager(@Autowired DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public TransactionPostProcessor transactionPostProcessor(){
        return new TransactionPostProcessor();
    }


}
